//
//  MainViewController.swift
//  weibo1990
//
//  Created by 曹晓龙 on 15/10/17.
//  Copyright © 2015年 曹晓龙. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    ///  发布信息按钮的点击
    @objc private func clickComposeBtn(){
        
        var vc = UIViewController()
        
        if OauthViewModel.sharedOauthViewModel.isLogin {
            
            
            vc = CXLComposeViewController()
            
            let nav = UINavigationController(rootViewController: vc)
            
            presentViewController(nav, animated: true, completion: nil)

            
        }else {
            
            vc = MainViewController()
            
            presentViewController(vc, animated: true, completion: nil)
        }
    }
    
    //MARK: - 视图声明周期
    override func viewDidLoad() {
        super.viewDidLoad()
        
        addChildViewControllers()
                
        addComposeBnt()
    }
    
    override func viewWillAppear(animated: Bool) {
        
        super.viewWillAppear(animated)
        
        tabBar.bringSubviewToFront(composeBtn)
    }
    
    // MARK: - 懒加载
    /// 懒加载中间发布信息按钮
    private lazy var composeBtn:UIButton = UIButton(imageName: "tabbar_compose_icon_add", backImageName: "tabbar_compose_button")

}

// MARK: - 添加子视图
extension MainViewController {
    
    ///  添加中间发布按钮
    private func addComposeBnt(){
 
        tabBar.addSubview(composeBtn)
        
        let count = childViewControllers.count
        
        let width = tabBar.bounds.width / CGFloat(count) - 1
        
        composeBtn.frame = CGRectInset(tabBar.bounds, 2 * width, 0)
        
        composeBtn.addTarget(self, action: "clickComposeBtn", forControlEvents: .TouchUpInside)
    }
    
    ///  添加子视图控制器到tabBar
    private func addChildViewControllers() {
        
        addChildViewController("首页", imageName: "tabbar_home", vc: HomeTableViewController())
        addChildViewController("消息", imageName: "tabbar_message_center", vc: MessageTableViewController())
        addChildViewController(UIViewController())
        addChildViewController("发现", imageName: "tabbar_discover", vc: DiscoverTableViewController())
        addChildViewController("我", imageName: "tabbar_profile", vc: ProfileTableViewController())
    }
    
    ///  添加每一个子视图
    ///
    ///  - parameter title:     标题
    ///  - parameter imageName: 图片名称
    private func addChildViewController(title:String, imageName:String, vc:UIViewController) {
        
        vc.title = title
        
        vc.tabBarItem.image = UIImage(named: imageName)
        
        let nav = UINavigationController(rootViewController: vc)
        
        addChildViewController(nav)
        
    }
    
}